package com.yangjun.service.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangjun.common.ServerResponse;
import com.yangjun.common.comparator.TargetItemComparator;
import com.yangjun.common.comparator.TargetItemComparatorByTargetArr;
import com.yangjun.common.enums.report.AnalysisTypeEnum;
import com.yangjun.common.enums.report.CaliberTypeEnum;
import com.yangjun.common.enums.report.OutstockTypeEnum;
import com.yangjun.common.enums.report.ReportTypeEnum;
import com.yangjun.common.excel.DataBaseExcelContext;
import com.yangjun.common.excel.ExcelExportResult;
import com.yangjun.dao.mybatis.mapper.report.DvReportSearchTmpMapper;
import com.yangjun.dao.mybatis.mapper.report.OrderTransactionReportExportMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportDownloadStatusMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportExportStatusMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportImportStatusMapper;
import com.yangjun.dao.mybatis2.mapper.common.CommonMapper;
import com.yangjun.entity.report.DvExcelFieldDefinitionEntity;
import com.yangjun.entity.report.DvReportDownloadStatusEntity;
import com.yangjun.entity.report.DvReportExportStatus;
import com.yangjun.entity.report.DwOrderTransactionEntity;
import com.yangjun.po.report.OrderTransactionReportExportPO;
import com.yangjun.service.common.CommonService;
import com.yangjun.service.permission.ReportExportPermissionService;
import com.yangjun.utils.DvDateUtils;
import com.yangjun.utils.DvUtils;
import com.yangjun.utils.POIExcelUtils;
import com.yangjun.vo.report.OrderTransactionReportExportVO;
import com.yangjun.vo.report.OrderTransactionReportManageVO;
@Service
public class OrderTransactionReprotExportService  {
	@Value("${excel.uploadPath}")
    private String uploadPath;
	@Value("${excel.downloadPath}")
    private String downloadPath;
	
	@Autowired
	private DataBaseExcelContext context;
	@Autowired
	private OrderTransactionReportExportMapper orderTransactionReportExportMapper;
	@Autowired
	private ReportExportStatusMapper reportExportStatusMapper;
	@Autowired
	private ReportImportStatusMapper reportImportStatusMapper;
	@Autowired
	private ReportDownloadStatusMapper reportDownloadStatusMapper;
	@Autowired
	private DvReportSearchTmpMapper dvReportSearchTmpMapper;
	@Autowired
	private CommonService commonService;
	@Autowired
	private ReportCommonService reportCommonService;
	@Autowired
	private ReportExportPermissionService reportExportPermissionService;
	@Autowired
	private CommonMapper commonMapper;
	private final static String reporttype = "orderTransaction";
	
	private String[] defaultOutstockOrderstatus = new String[]{"完全生成","部分生成","已审核","已付款","完全出库","已完成","部分出库"};
	private String[] defaultThirdOutstockOrderstatus = new String[]{"完全出库","已完成","部分出库"};

	/**
	 * @Description 获取维度信息
	 * @return
	 * @author yangjun
	 * @Date 2017年7月5日 上午11:50:06
	 */
	//fetchType(取数类型) : 临时(temporary)订阅(subscription)
	//summaryCycle(汇总周期) : naturalDay(自然天)naturalWeek(自然周)naturalMonth(自然月)custom(自定义)
	public Object getDeminsion(String reportid,String userid){
		OrderTransactionReportExportVO otreVo = null;
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		
		String reportName = "订单交易-";
		String uploadFileId = "";
		String uploadFileName = "";
		String searchName = "";
		//平台
		String[] saveOrdersourceArr = null;
		int type = reportExportPermissionService.getManagerType(userid, reporttype);
		List<Map<String, Object>> ordersource = commonService.getOrderSource(type,userid,reporttype);
		//取数类型(默认临时取数)
		String fetchType = ReportTypeEnum.temporary.getValue();
		//报表选择
		String analysisType = null;
		List<Map<String,Object>> analysisTypeList = AnalysisTypeEnum.getAnalysisTypeMap(commonService.getOrderAnalysisType(userid, reporttype));
		//口径
		String caliberType = CaliberTypeEnum.ordered.getValue();
		
		//查询开始时间(默认都是31天前)
		String beginDate = DvDateUtils.getDate(new Date(), -31);
		//查询结束时间(默认都是昨天)
		String endDate = DvDateUtils.getDate(new Date(), -1);
		
		Boolean modify = dvReportExportStatus!=null?true:false;
		
		//出库类型
		String[] outstockType = null;
		String[] orderStatus = new String[]{};
		String[] payType = null;
		//选择的指标
		String[] targetSelectData  = null;

		if(dvReportExportStatus!=null){
			otreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), OrderTransactionReportExportVO.class);
			targetSelectData = otreVo.getTarget();
			reportName = otreVo.getReportName();
			uploadFileId = otreVo.getUploadFileId();
			if(StringUtils.isNotBlank(uploadFileId)){
				uploadFileName = reportImportStatusMapper.queryReportStatusByUUID(uploadFileId).getReportName();
			}
			saveOrdersourceArr = otreVo.getOrdersource();
			fetchType = otreVo.getFetchType();
			analysisType = otreVo.getAnalysisType();

			caliberType = otreVo.getCaliberType();
			//保存是用中文，查询用英文
			outstockType = otreVo.getOutstockType();
			
			orderStatus = otreVo.getOrderstatus();
			payType = otreVo.getPayType();
			
			beginDate = otreVo.getBeginDate();
			endDate = otreVo.getEndDate();
			
			searchName = otreVo.getSearchName();
		}
		Map<String,Object> demensionMap = Maps.newHashMap();
		//平台
		for(Map<String, Object> ordersourceItem : ordersource){
			if(saveOrdersourceArr!=null){
				ordersourceItem.put("checked", false);
				String[] os = ordersourceItem.get("ordersource").toString().split(",");
				for(String osItem : os){
					if(ArrayUtils.contains(saveOrdersourceArr, osItem)){
						ordersourceItem.put("checked", true);
					}
				}
			}else{
				ordersourceItem.put("checked", true);
			}
		}
		demensionMap.put("ordersource",ordersource);
		//取数类型
		demensionMap.put("fetchType",fetchType);
		//报表选择
		Boolean selectAnalysisType = false;
		if(analysisType!=null){
			for(Map<String,Object> item : analysisTypeList){
					String value = item.get("value").toString();
					if(value.equals(analysisType)){
						item.put("checked", true);
						selectAnalysisType = true;
					}else{
						item.put("checked", false);
					}
			}
			if(!selectAnalysisType){
				return ServerResponse.createByErrorMessage("报表类型权限不足，请修改报表！");
			}
		}
		demensionMap.put("analysisType",analysisTypeList);
		//口径
		demensionMap.put("caliberType",caliberType);
		//出库方式
		demensionMap.put("outstockType",commonService.HandleCheackBoxStatus(OutstockTypeEnum.getOutstockName(),outstockType));
		//支付方式
		demensionMap.put("payType",commonService.HandleCheackBoxStatus(orderTransactionReportExportMapper.queryPayType(),payType));

		//查询日期
		demensionMap.put("dateMethod", queryDateMethod(modify,beginDate,endDate));
		
		//报表名
		demensionMap.put("reportName",reportName);
		//上传文件名
		demensionMap.put("uploadFileName", uploadFileName);
		//上传文件ID
		demensionMap.put("uploadFileId", uploadFileId);
		
		//报表类型
		demensionMap.put("reporttype", reporttype);

		//订单状态
		demensionMap.put("orderStatus",StringUtils.join(orderStatus,","));
		//选择的指标
		demensionMap.put("selectTarget",StringUtils.join(targetSelectData,","));
		demensionMap.put("searchName", searchName);
		//更新时间
		demensionMap.put("update", "每天 整点");

		
		reportCommonService.deleteUploadReport(userid);
		return ServerResponse.createBySuccess(demensionMap);
	}
	
	public Object queryOrderstatus(String caliberType,String[] outstockType,String[] orderstatus){
		if(CaliberTypeEnum.ordered.getValue().equals(caliberType)){
			return ServerResponse.createBySuccess(commonService.HandleCheackBoxStatus(orderTransactionReportExportMapper.queryOrderStatus(),orderstatus));
		}else if(CaliberTypeEnum.outstock.getValue().equals(caliberType)){
			//出库的只能看部分订单状态,出库的自主出库也只能看部分其中的部分
			if(outstockType.length==1&&outstockType[0].equals(OutstockTypeEnum.self_outstock.getName())){
				return ServerResponse.createBySuccess(commonService.HandleCheackBoxStatus(Arrays.asList(defaultThirdOutstockOrderstatus),orderstatus));
			}
			return ServerResponse.createBySuccess(commonService.HandleCheackBoxStatus(Arrays.asList(defaultOutstockOrderstatus),orderstatus));
		}else{
			return ServerResponse.createBySuccess(Lists.newArrayList());
		}
		
	}
	public Object queryTarget(String userid,String caliberType,String[] targetSelectData){
		Map<String,Object> demensionMap = Maps.newHashMap();
		//修改报表排序号的字段顺序
		List<Map<String,Object>> sortTargetSelectData=Lists.newArrayList();
		//获取每个报表的指标分类
		List<DvExcelFieldDefinitionEntity> excelFieldDefinitionList = reportCommonService.getExcelFieldDefinitionList(reporttype,caliberType);
		Map<String,String> tmpCategoryMap = reportCommonService.queryCategory(reporttype);
		List<Map<String,String>> categoryList = Lists.newArrayList();

		Map<String,List<Map<String,Object>>> targetMap = Maps.newHashMap();
		List<Map<String,Object>> targetList =null;
		for(Map.Entry<String,String> categoryEntry: tmpCategoryMap.entrySet()){
			//初始化指标分类数组
			Map<String,String> categoryMap = Maps.newHashMap();
			categoryMap.put("name", categoryEntry.getKey());
			categoryMap.put("value", categoryEntry.getValue());
			categoryList.add(categoryMap);
			//初始化指标分类内容
			targetList = Lists.newArrayList();
			targetMap.put(categoryEntry.getKey(),targetList);
		}
		demensionMap.put("category", categoryList);
		//查询有权限显示的报表字段
		String[] allowFieldArr = reportExportPermissionService.getReportAllowField(userid, reporttype);
		if(allowFieldArr!=null&&allowFieldArr.length>0){
			for(DvExcelFieldDefinitionEntity excelFieldDefinitionEntity : excelFieldDefinitionList){
				//权限控制能够显示的字段，如果查询不到对应角色的权限直接不显示字段。
				//&&("18".equals(userid)||"507".equals(userid)||"715".equals(userid)||"6".equals(userid)||"518".equals(userid)||"141".equals(userid)||"481".equals(userid))
				if(allowFieldArr!=null){
					List<String> allowFieldList = Arrays.asList(allowFieldArr);
					if(!allowFieldList.contains(excelFieldDefinitionEntity.getEntityName())){
						continue;
					}
				}
				//封装默认的指标格式
				String categoryId = excelFieldDefinitionEntity.getCategoryId();
				if(StringUtils.isNotBlank(categoryId)){
					String entityName = excelFieldDefinitionEntity.getEntityName();
					String title = excelFieldDefinitionEntity.getTitle();
					int sort = excelFieldDefinitionEntity.getFieldSort();
					Map<String,Object> itemMap = Maps.newHashMap();
					itemMap.put("value", entityName);
					itemMap.put("name", title);
					itemMap.put("sort", sort);
					itemMap.put("checked", false);
					if(targetSelectData!=null){
						for(int i=0,len=targetSelectData.length;i<len;i++){
							if(entityName.equals(targetSelectData[i])){
								itemMap.put("checked", true);
								//修改报表排序号的字段顺序
								sortTargetSelectData.add(itemMap);
							}
						}					
					}
					targetList = targetMap.get(categoryId);
					//已经在上面初始化了不用判断空
					targetList.add(itemMap);
				}
			}
			//根据数据库给定的sort字段进行排序
			for(Map.Entry<String,List<Map<String,Object>>> targetItemEntry : targetMap.entrySet()){
					Collections.sort(targetItemEntry.getValue(),new TargetItemComparator());
			}
		}
		//指标
		demensionMap.put("target", targetMap);
		Collections.sort(sortTargetSelectData, new TargetItemComparatorByTargetArr(targetSelectData));
		demensionMap.put("sortTarget", sortTargetSelectData);
		return ServerResponse.createBySuccess(demensionMap);
	}

	public Object querySearch(String analysisType,String caliberType,String searchName){
		String[] orderDetailOrderedTemplate = new String[]{"wareCode","department",
				"manufacturer","activeCode","shop","orderchannel","ordercode"
				,"thirdOrdercode","trackcode","packagecode","buyer"};
		String[] orderDetailOutstockTemplate = orderDetailOrderedTemplate;
		String[] orderDetailReturnTemplate = new String[]{"wareCode","returncode","ordercode","thirdOrdercode","buyer"};
		
		String[] orderMainOrderedTemplate =new String[]{"shop","orderchannel","ordercode"
				,"thirdOrdercode","trackcode","packagecode","buyer"};
		String[] orderMainOutstockTemplate = orderMainOrderedTemplate;
		String[] orderMainReturnTemplate = new String[]{"returncode","ordercode","thirdOrdercode","buyer"};
		if(StringUtils.isBlank(searchName)&&AnalysisTypeEnum.orderDetail.getValue().equals(analysisType)){
			searchName="wareCode";
		}
		if(CaliberTypeEnum.ordered.getValue().equals(caliberType)){
			if(AnalysisTypeEnum.orderMain.getValue().equals(analysisType)){
				if(StringUtils.isBlank(searchName)){
					searchName="shop";
				}
				return ServerResponse.createBySuccess(reportCommonService.getSearchTemplate(orderMainOrderedTemplate,searchName));
			}
			return ServerResponse.createBySuccess(reportCommonService.getSearchTemplate(orderDetailOrderedTemplate,searchName));
		}else if(CaliberTypeEnum.outstock.getValue().equals(caliberType)){
			if(AnalysisTypeEnum.orderMain.getValue().equals(analysisType)){
				if(StringUtils.isBlank(searchName)){
					searchName="shop";
				}
				return ServerResponse.createBySuccess(reportCommonService.getSearchTemplate(orderMainOutstockTemplate,searchName));
			}
			return ServerResponse.createBySuccess(reportCommonService.getSearchTemplate(orderDetailOutstockTemplate,searchName));
		}else if(CaliberTypeEnum.returned.getValue().equals(caliberType)){
			if(AnalysisTypeEnum.orderMain.getValue().equals(analysisType)){
				if(StringUtils.isBlank(searchName)){
					searchName="returncode";
				}
				return ServerResponse.createBySuccess(reportCommonService.getSearchTemplate(orderMainReturnTemplate,searchName));
			}
			return ServerResponse.createBySuccess(reportCommonService.getSearchTemplate(orderDetailReturnTemplate,searchName));
		}else{
			return ServerResponse.createBySuccess(Lists.newArrayList());
		}
	}
	
	private Object queryDateMethod(Boolean modify,String beginDate,String endDate){
		//summaryCycle(汇总周期) : naturalDay(自然天)naturalWeek(自然周)naturalMonth(自然月)custom(自定义)
		Map<String,Object> resultMap = Maps.newHashMap();
		String[] fetchTypeArr = {"temporary","subscription"};
		for(String fetchTypeItem : fetchTypeArr ){
			if("temporary".equals(fetchTypeItem)){
				//临时取数
				resultMap.put(fetchTypeItem, queryDateOfTemporaryWay(beginDate,endDate));
			}else if("subscription".equals(fetchTypeItem)){
				//订阅报表
				resultMap.put(fetchTypeItem, queryDateOfSubscriptionWay(modify,beginDate,endDate));
			}
		}
		return resultMap;
	}
	private Map<String,Object> queryDateOfTemporaryWay(String beginDate,String endDate){
		Map<String,Object> temporaryDate = Maps.newHashMap();
		//开始时间
		temporaryDate.put("beginDate", beginDate);
		//结束时间
		temporaryDate.put("endDate", endDate);
		return temporaryDate;
	}
	private List<Map<String,String>> queryDateOfSubscriptionWay(Boolean modify,String beginDate,String endDate){
				//自然天，过去7天，默认第一个选中
				List<Map<String,String>> naturalDayList = Lists.newArrayList();
				String edOfNaturalDay = DvDateUtils.getDate(new Date(), -1);
				for(int i=1;i<=7;i++){
					Map<String,String> naturalDayMap = Maps.newHashMap();
					String checked = "false";
					String bdOfNaturalDay = DvDateUtils.getDate(new Date(), -i);
					naturalDayMap.put("name","过去"+i+"天");
					naturalDayMap.put("beginDate",bdOfNaturalDay);
					naturalDayMap.put("endDate",edOfNaturalDay);
					if(modify){
						if(bdOfNaturalDay.equals(beginDate)&&edOfNaturalDay.equals(endDate)){
							checked = "true";
						}
					}else{
						if(i==1){
							checked = "true";
						}
					}
					naturalDayMap.put("checked",checked);
					naturalDayList.add(naturalDayMap);
				}
		return naturalDayList;

	}
	private List<String> getTargetList(String analysisType,String[] targetArr){
		List<String> targetList = Lists.newArrayList();
		String[] defaultArr = new String[]{"ordercode","warecode","warename"};
		if(AnalysisTypeEnum.orderDetail.getValue().equals(analysisType)){
			for(String defaultItem : defaultArr){
				targetList.add(defaultItem);
			}
		}else if(AnalysisTypeEnum.orderMain.getValue().equals(analysisType)){
			targetList.add(defaultArr[0]);
		}
		for(String targetItem : targetArr){
			targetList.add(targetItem);
		}
		return targetList;
	}
	
	
	public Object queryData(String reportid){
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		OrderTransactionReportExportVO otreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), OrderTransactionReportExportVO.class);
		return queryData(otreVo);
	}
	public Object queryData(OrderTransactionReportExportVO otreVo){
		if(otreVo.getOrdersource()==null||otreVo.getOrdersource().length<1){
			return ServerResponse.createByErrorMessage("平台为空,请修改报表！");
		}
		if(StringUtils.isBlank(otreVo.getAnalysisType())){
			return ServerResponse.createByErrorMessage("报表选择为空,请修改报表！");
		}
		OrderTransactionReportExportPO otrePo= new OrderTransactionReportExportPO();

		Map<String,Object> resultMap = Maps.newHashMap();
		String[] targetArr = otreVo.getTarget();
		List<String> targetList = getTargetList(otreVo.getAnalysisType(), targetArr);
		handleTargetSql(otrePo,targetList);
		
		Long start = System.currentTimeMillis();
		List<DvExcelFieldDefinitionEntity>  reportFieldDefinition= reportCommonService.getExcelFieldDefinitionList(reporttype);
		//装载表格数据
		List<List<String>> tableList = Lists.newArrayList();

		List<String> titleList = Lists.newArrayList();
		for(String item : targetList){
			for(DvExcelFieldDefinitionEntity definition : reportFieldDefinition){
				String name = definition.getEntityName();
				if(item.equals(name)){
					titleList.add(definition.getTitle());
				}
			}
		}
		tableList.add(titleList);
		System.out.println("1."+(System.currentTimeMillis()-start)/1000);
		
		List<String> searchItemList = Lists.newArrayList();
		//查找附件内容作为搜索条件
			if(StringUtils.isNotBlank(otreVo.getUploadFileId())){
				int partSize=1000;
				String fileName = reportImportStatusMapper.queryReportStatusByUUID(otreVo.getUploadFileId()).getFileName();
				File uploadFile = new File(uploadPath+fileName);
				FileInputStream readStream = null;
				try {
					readStream = new FileInputStream(uploadFile);
					List<List<Object>> datas =POIExcelUtils.readExcel(readStream, 0);
					for(int i=0,len=datas.size();i<len;i++){
						if(i>0&&datas.get(i).get(0)!=null){
							searchItemList.add(datas.get(i).get(0).toString());
						}
					}
					dvReportSearchTmpMapper.deleteDvReportSearchTmp(otreVo.getUserid());
					if(searchItemList.size()>partSize){
						int part = searchItemList.size()/partSize;
						for(int i=0;i<part;i++){
							List<String> tmpList  = searchItemList.subList(0, partSize);
							dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(otreVo.getUserid(), tmpList);
							searchItemList.subList(0, partSize).clear();
						}
					}
					if(searchItemList.size()>0){
						dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(otreVo.getUserid(), searchItemList);
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				otreVo.setSearchValue(searchItemList.size()>0?searchItemList.toArray(new String[searchItemList.size()]):null);
			}else{
				otreVo.setSearchValue(null);
			}
		System.out.println("2."+(System.currentTimeMillis()-start)/1000);
		BeanUtils.copyProperties(otreVo, otrePo);
		otrePo.changeOutsockType();
		//根据权限进行查询或者下载，单品分析页面要判断用户是否是属于商品经理订阅的报表，如果是对应的商品经理只能下载所管理的商品否则可以下载全部商品根据(0是1不是-1找不到角色，有问题可咨询庄曼娜李建华)
		int type = reportExportPermissionService.getManagerType(otrePo.getUserid(), reporttype);
		//商品经理过滤 有数据就去掉之前的逻辑否则不用。
		List<String> names = commonMapper.getNoFilterGoodsManager(otrePo.getUsername());
		if(names!=null && names.size()>0){
			type = 1;
		}
		List<DwOrderTransactionEntity> list = orderTransactionReportExportMapper.queryData(otrePo, 1, 10,type);
		System.out.println("单品分析查询数据 list:"+list.size()+" type:"+type);
		JSONArray objectArr = JSON.parseArray(JSONObject.toJSONString(list));
		for(int i = 0,len = objectArr.size() ; i<len ; i++){
			JSONObject object = objectArr.getJSONObject(i);
			List<String> itemList = Lists.newArrayList();
			for(String item : targetList){
				itemList.add(object.getString(item)==null?"":object.getString(item));
			}
			tableList.add(itemList);
		}
		System.out.println("3."+(System.currentTimeMillis()-start)/1000);
		resultMap.put("tableData",tableList );
		resultMap.put("rownum",list.size()>0?list.get(0).getCountNum():0);
		return ServerResponse.createBySuccess(resultMap);
	}
	

	public Object addOrUpdateReport(OrderTransactionReportExportVO otreVo){
		String reportid = otreVo.getReportid();
		List<String> targetNameList = Lists.newArrayList();
		String[] targetArr = otreVo.getTarget();

		List<DvExcelFieldDefinitionEntity> excelFieldDefinitionList = reportCommonService.getExcelFieldDefinitionList(reporttype);
		for(String target : targetArr){
			for(DvExcelFieldDefinitionEntity dvExcelFieldDefinitionItem : excelFieldDefinitionList){
				String entityName = dvExcelFieldDefinitionItem.getEntityName();
				String targetName = dvExcelFieldDefinitionItem.getTitle();
					if(target.equals(entityName)){
						targetNameList.add(targetName);
					}
			}
		}
		int type = reportExportPermissionService.getManagerType(otreVo.getUserid(), reporttype);
		OrderTransactionReportManageVO orderTransactionReportManageVO = new OrderTransactionReportManageVO();
		BeanUtils.copyProperties(otreVo, orderTransactionReportManageVO);
		orderTransactionReportManageVO.setReportid(reportid);
		//权限修改了平台ID,对应的平台名称也要变
		orderTransactionReportManageVO.setSourcename(reportCommonService.getOrderSourceName(otreVo.getOrdersource(), commonService.getOrderSource( type, otreVo.getUserid(),reporttype)));
		orderTransactionReportManageVO.setTargetName(targetNameList);
		orderTransactionReportManageVO.setSaveTime(DvDateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
		//添加附件名字
		if(StringUtils.isNotBlank(otreVo.getUploadFileId())){
			String uploadFileName = reportImportStatusMapper.queryReportStatusByUUID(otreVo.getUploadFileId()).getReportName();
			otreVo.setUploadFileName(uploadFileName);
			orderTransactionReportManageVO.setUploadFileName(otreVo.getUploadFileName());
		}
		if(StringUtils.isNotBlank(reportid)){
			DvReportExportStatus dvReportExportStatus = new DvReportExportStatus();
			dvReportExportStatus.setReportid(reportid);
			dvReportExportStatus.setReportName(otreVo.getReportName());
			dvReportExportStatus.setReportparam(JSON.toJSONString(otreVo));
			dvReportExportStatus.setReportManageParam(JSON.toJSONString(orderTransactionReportManageVO));
			if(reportExportStatusMapper.updateReportStatus(dvReportExportStatus)>0){
				return ServerResponse.createBySuccessMessage("修改报表成功!");
			}else{
				return ServerResponse.createBySuccessMessage("修改报表失败!");
			}
		}else{
			//加入报表前需要根据用户ID，报表名去判断是否有重名的报表
			if(reportExportStatusMapper.queryReport(otreVo.getUserid(), otreVo.getReportName())>0){
				return ServerResponse.createByErrorMessage("已存在相同名称的报表，请重新命名!");
			}else{
				reportid = reporttype+String.valueOf(System.currentTimeMillis())+String.valueOf((int)((Math.random()*9+1)*100000));
				otreVo.setReportid(reportid);
				orderTransactionReportManageVO.setReportid(reportid);
				DvReportExportStatus dvReportExportStatus = new DvReportExportStatus();
				BeanUtils.copyProperties(otreVo, dvReportExportStatus);
				dvReportExportStatus.setCreatetime(new Date());
				dvReportExportStatus.setReportparam(JSON.toJSONString(otreVo));
				dvReportExportStatus.setReportManageParam(JSON.toJSONString(orderTransactionReportManageVO));
				dvReportExportStatus.setReporttype(reporttype);
				dvReportExportStatus.setFileName(otreVo.getUploadFileId()+otreVo.getUploadFileName());
				if(reportExportStatusMapper.insertReportStatus(dvReportExportStatus)>0){
					return ServerResponse.createBySuccessMessage("添加报表成功!");
				}else{
					return ServerResponse.createByErrorMessage("添加报表失败!");
				}
			}
		}
	}
	

	public Object download(OrderTransactionReportExportVO otreVo,HttpServletRequest request){
		context.initDBExcelDefinitionReader("export");
		OrderTransactionReportExportPO otrePo= new OrderTransactionReportExportPO();
		String[] targetArr = otreVo.getTarget();
		List<String> targetList = getTargetList(otreVo.getAnalysisType(), targetArr);
		//处理查询的sql
		handleTargetSql(otrePo,targetList);
		List<String> searchItemList = Lists.newArrayList();
		//查找附件内容作为搜索条件
		if(StringUtils.isNotBlank(otreVo.getUploadFileId())){
			int partSize=1000;
			String fileName = reportImportStatusMapper.queryReportStatusByUUID(otreVo.getUploadFileId()).getFileName();
			File uploadFile = new File(uploadPath+fileName);
			FileInputStream readStream = null;
			try {
				readStream = new FileInputStream(uploadFile);
				List<List<Object>> datas =POIExcelUtils.readExcel(readStream, 0);
				for(int i=0,len=datas.size();i<len;i++){
					if(i>0&&datas.get(i).get(0)!=null){
						searchItemList.add(datas.get(i).get(0).toString());
					}
				}
				dvReportSearchTmpMapper.deleteDvReportSearchTmp(otreVo.getUserid());
				if(searchItemList.size()>partSize){
					int part = searchItemList.size()/partSize;
					for(int i=0;i<part;i++){
						List<String> tmpList  = searchItemList.subList(0, partSize);
						dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(otreVo.getUserid(), tmpList);
						searchItemList.subList(0, partSize).clear();
					}
				}
				if(searchItemList.size()>0){
					dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(otreVo.getUserid(), searchItemList);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			otreVo.setSearchValue(searchItemList.size()>0?searchItemList.toArray(new String[searchItemList.size()]):null);
		}else{
			otreVo.setSearchValue(null);
		}
		BeanUtils.copyProperties(otreVo, otrePo);
		//修改出库类型
		otrePo.changeOutsockType();
		//用户ID，UUID组成下载ID
		String downloadId = otreVo.getUserid()+UUID.randomUUID().toString().replaceAll("-", "");
		String downloadReportName = otreVo.getReportName();
		String fileName =downloadId+downloadReportName+".xlsx";
		int type = reportExportPermissionService.getManagerType(otrePo.getUserid(), reporttype);
		//商品经理过滤 有数据就去掉之前的逻辑否则不用。
		List<String> names = commonMapper.getNoFilterGoodsManager(otrePo.getUsername());
		if(names!=null && names.size()>0){
			type = 1;
		}
		System.out.println(otrePo);
		System.out.println(type);
		int rownum = orderTransactionReportExportMapper.queryCount(otrePo,type);
		System.out.println(rownum);
		DvReportDownloadStatusEntity dvReportDownloadStatusEntity = new DvReportDownloadStatusEntity();
		dvReportDownloadStatusEntity.setDownloadId(downloadId);
		dvReportDownloadStatusEntity.setFileName(fileName);
		dvReportDownloadStatusEntity.setReportName(downloadReportName);
		dvReportDownloadStatusEntity.setReportType(reporttype);
		dvReportDownloadStatusEntity.setUserid(otreVo.getUserid());
		dvReportDownloadStatusEntity.setUsername(otreVo.getUsername());
		dvReportDownloadStatusEntity.setUserrealname(otreVo.getUserrealname());
		dvReportDownloadStatusEntity.setTargetName(JSON.toJSONString(reportCommonService.getTargetNameList(targetArr, reporttype)));
		dvReportDownloadStatusEntity.setIp(DvUtils.getIp(request));
		if(reportDownloadStatusMapper.insertReport(dvReportDownloadStatusEntity)>0){
			DownloadTask downloadTask = new DownloadTask(fileName,targetList,rownum,otrePo,dvReportDownloadStatusEntity,type);
			new Thread(downloadTask).start();  
			return ServerResponse.createBySuccessMessage("加入下载列表成功！");
		}else{
			return ServerResponse.createByErrorMessage("加入下载列表失败！");
		}
	}
	public Object addDownloadTask(String reportid,HttpServletRequest request){
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		OrderTransactionReportExportVO orreVo = JSON.parseObject(dvReportExportStatus.getReportparam(), OrderTransactionReportExportVO.class);
		return download(orreVo,request);
	}
	public Object addDownloadTask(OrderTransactionReportExportVO otreVo,HttpServletRequest request){
		if(reportDownloadStatusMapper.queryReportByName(otreVo.getUserid(), otreVo.getReportName())>0){
			return ServerResponse.createByErrorMessage("已存在相同名称的报表，请重新命名!");
		}else{
			return download(otreVo,request);
		}
	}
	
	class DownloadTask implements Runnable{
		public  boolean flag = true;  
		private String fileName;
		private Integer rownum;
		private List<String> targetList;
		private OrderTransactionReportExportPO otrePo;
		private DvReportDownloadStatusEntity dvReportDownloadStatusEntity;
		private int type;
		public DownloadTask(String fileName,List<String> targetList,int rownum,OrderTransactionReportExportPO otrePo,DvReportDownloadStatusEntity dvReportDownloadStatusEntity,int type){
			this.fileName = fileName;
			this.rownum = rownum;
			this.targetList = targetList;
			this.otrePo = otrePo;
			this.dvReportDownloadStatusEntity = dvReportDownloadStatusEntity;
			this.type = type;
		}
		public void stopThread(){
			flag = false;
		}
		@Override
		public void run() {
			while (flag){
				long a = System.currentTimeMillis();
				OutputStream ops = null;
				ExcelExportResult exportResult = null;
				try {
					ops = new FileOutputStream(downloadPath+fileName);
					exportResult = context.createEmptyExcelForPart(reporttype,DwOrderTransactionEntity.class,targetList);
					int pageSize = 40000;
					int totalPage = (int)Math.ceil(rownum/pageSize);
					totalPage += rownum%pageSize>0?1:0; 
					for(int i=1;i<=totalPage;i++){
						exportResult.append(orderTransactionReportExportMapper.queryData(otrePo, i, pageSize, type));
					}
				Workbook workbook = exportResult.build();
				workbook.write(ops);
				ops.flush();
				ops.close();
				workbook.close();
				long b = System.currentTimeMillis();
				System.out.println("耗时："+(b-a));
				dvReportDownloadStatusEntity.setEndDate(new Date());
				dvReportDownloadStatusEntity.setTimeConsume(Math.round(dvReportDownloadStatusEntity.getEndDate().getTime()-dvReportDownloadStatusEntity.getBeginDate().getTime())/1000);
				dvReportDownloadStatusEntity.setDownloadFlag(1);
				reportDownloadStatusMapper.updateReportById(dvReportDownloadStatusEntity);
				this.stopThread();
				} catch (Exception e) {
					System.out.println("OrderTransactionReprot awaitTermination interrupted: " + e);  
					this.stopThread();
				}
			}
		}
	}
	private void handleTargetSql(OrderTransactionReportExportPO otrePo,List<String> targetList){
		for(String target : targetList){
			if(target.equals("createdate")){
				otrePo.setCreatedateSql(true);
			}else if(target.equals("dataDate")){
				otrePo.setDataDateSql(true);
			}else if(target.equals("orgname")){
				otrePo.setOrgnameSql(true);
			}else if(target.equals("consigncode")){
				otrePo.setConsigncodeSql(true);
			}else if(target.equals("consignweight")){
				otrePo.setConsignweightSql(true);
			}else if(target.equals("deliverynumber")){
				otrePo.setDeliverynumberSql(true);
			}else if(target.equals("deliverycompany")){
				otrePo.setDeliverycompanySql(true);
			}else if(target.equals("province")){
				otrePo.setProvinceSql(true);
			}else if(target.equals("city")){
				otrePo.setCitySql(true);
			}else if(target.equals("district")){
				otrePo.setDistrictSql(true);
			}else if(target.equals("warecode")){
				otrePo.setWarecodeSql(true);
			}else if(target.equals("warename")){
				otrePo.setWarenameSql(true);
			}else if(target.equals("model")){
				otrePo.setModelSql(true);
			}else if(target.equals("manufacturername")){
				otrePo.setManufacturernameSql(true);
			}else if(target.equals("facategory")){
				otrePo.setFacategorySql(true);
			}else if(target.equals("department")){
				otrePo.setDepartmentSql(true);
			}else if(target.equals("isrx")){
				otrePo.setIsrxSql(true);
			}else if(target.equals("isthirdgoods")){
				otrePo.setIsthirdgoodsSql(true);
			}else if(target.equals("waremanagerpc")){
				otrePo.setWaremanagerpcSql(true);
			}else if(target.equals("outqty")){
				otrePo.setOutqtySql(true);
			}else if(target.equals("price")){
				otrePo.setPriceSql(true);
			}else if(target.equals("disprice")){
				otrePo.setDispriceSql(true);
			}else if(target.equals("alldisprice")){
				otrePo.setAlldispriceSql(true);
			}else if(target.equals("netprice")){
				otrePo.setNetpriceSql(true);
			}else if(target.equals("netamount")){
				otrePo.setNetamountSql(true);
			}else if(target.equals("concession")){
				otrePo.setConcessionSql(true);
			}else if(target.equals("pointsamt")){
				otrePo.setPointsamtSql(true);
			}else if(target.equals("outamount")){
				otrePo.setOutamountSql(true);
			}else if(target.equals("fadisprice")){
				otrePo.setFadispriceSql(true);
			}else if(target.equals("faalldisprice")){
				otrePo.setFaalldispriceSql(true);
			}else if(target.equals("faprice")){
				otrePo.setFapriceSql(true);
			}else if(target.equals("faamount")){
				otrePo.setFaamountSql(true);
			}else if(target.equals("faconcession")){
				otrePo.setFaconcessionSql(true);
			}else if(target.equals("fapointsamt")){
				otrePo.setFapointsamtSql(true);
			}else if(target.equals("faoutamount")){
				otrePo.setFaoutamountSql(true);
			}else if(target.equals("inprice")){
				otrePo.setInpriceSql(true);
			}else if(target.equals("purchasecost")){
				otrePo.setPurchasecostSql(true);
			}else if(target.equals("marketingcost")){
				otrePo.setMarketingcostSql(true);
			}else if(target.equals("grossprofit")){
				otrePo.setGrossprofitSql(true);
			}else if(target.equals("freightcost")){
				otrePo.setFreightcostSql(true);
			}else if(target.equals("fagrossprofit")){
				otrePo.setFagrossprofitSql(true);
			}else if(target.equals("fafreightcost")){
				otrePo.setFafreightcostSql(true);
			}else if(target.equals("sourcename")){
				otrePo.setSourcenameSql(true);
			}else if(target.equals("shopname")){
				otrePo.setShopnameSql(true);
			}else if(target.equals("channelname")){
				otrePo.setChannelnameSql(true);
			}else if(target.equals("consignstatus")){
				otrePo.setConsignstatusSql(true);
			}else if(target.equals("drpordercode")){
				otrePo.setDrpordercodeSql(true);
			}
			else if(target.equals("ordercode")){
				otrePo.setOrdercodeSql(true);
			}else if(target.equals("originorderid")){
				otrePo.setOriginorderidSql(true);
			}else if(target.equals("changetype")){
				otrePo.setChangetypeSql(true);
			}else if(target.equals("orderstatus")){
				otrePo.setOrderstatusSql(true);
			}else if(target.equals("stockstatus")){
				otrePo.setStockstatusSql(true);
			}else if(target.equals("sumamt")){
				otrePo.setSumamtSql(true);
			}else if(target.equals("orderfreightcost")){
				otrePo.setOrderfreightcostSql(true);
			}else if(target.equals("appendfreightcost")){
				otrePo.setAppendfreightcostSql(true);
			}else if(target.equals("prmcode")){
				otrePo.setPrmcodeSql(true);
			}else if(target.equals("prmname")){
				otrePo.setPrmnameSql(true);
			}else if(target.equals("disamt")){
				otrePo.setDisamtSql(true);
			}else if(target.equals("orderpointsamt")){
				otrePo.setOrderpointsamtSql(true);
			}else if(target.equals("netamt")){
				otrePo.setNetamtSql(true);
			}else if(target.equals("unpaidamt")){
				otrePo.setUnpaidamtSql(true);
			}else if(target.equals("payconcode")){
				otrePo.setPayconcodeSql(true);
			}else if(target.equals("paystatus")){
				otrePo.setPaystatusSql(true);
			}else if(target.equals("cuscode")){
				otrePo.setCuscodeSql(true);
			}else if(target.equals("cusname")){
				otrePo.setCusnameSql(true);
			}else if(target.equals("ordernumber")){
				otrePo.setOrdernumberSql(true);
			}else if(target.equals("isNewMember")){
				otrePo.setIsNewMemberSql(true);
			}else if(target.equals("creatorcode")){
				otrePo.setCreatorcodeSql(true);
			}else if(target.equals("creator")){
				otrePo.setCreatorSql(true);
			}else if(target.equals("returnid")){
				otrePo.setReturnidSql(true);
			}else if(target.equals("orderReturnamount")){
				otrePo.setOrderReturnamountSql(true);
			}else if(target.equals("orderFareturnamount")){
				otrePo.setOrderFareturnamountSql(true);
			}else if(target.equals("refunddetailcause")){
				otrePo.setRefunddetailcauseSql(true);
			}else if(target.equals("remark")){
				otrePo.setRemarkSql(true);
			}else if(target.equals("returntype")){
				otrePo.setReturntypeSql(true);
			}else if(target.equals("stocktime")){
				otrePo.setStocktimeSql(true);
			}else if(target.equals("stockcount")){
				otrePo.setStockcountSql(true);
			}else if(target.equals("returnprice")){
				otrePo.setReturnpriceSql(true);
			}else if(target.equals("returnamount")){
				otrePo.setReturnamountSql(true);
			}else if(target.equals("fareturnprice")){
				otrePo.setFareturnpriceSql(true);
			}else if(target.equals("fareturnamount")){
				otrePo.setFareturnamountSql(true);
			}else if(target.equals("tmstaff")){
				otrePo.setTmstaffSql(true);
			}else if(target.equals("invoicetype")){
				otrePo.setInvoicetypeSql(true);
			}else if(target.equals("cpsUtmMedium")){
				otrePo.setCps_utm_mediumSql((true));
			}else if(target.equals("cpsUtmSource")){
				otrePo.setCps_utm_sourceSql((true));
			}else if(target.equals("taxrate")){
				otrePo.setTaxrateSql(true);
			}else if(target.equals("invoicecontentcode2")){
				otrePo.setInvoicecontentcode2Sql((true));
			}else if(target.equals("paytypename")){
				otrePo.setPaytypenameSql((true));
			}else if(target.equals("sales")){
				otrePo.setSalesSql((true));
			}else if(target.equals("notaxfagrossprofit")){
				otrePo.setNotaxfagrossprofitSql(true);
			}else if(target.equals("notaxfareturnamount")){
				otrePo.setNotaxfareturnamountSql((true));
			}else if(target.equals("notaxfaoutamount")){
				otrePo.setNotaxfaoutamountSql((true));
			}
		}
	}

}
